package com.study.rpc03.client;

import com.study.common.IUserService;
import com.study.common.User;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * 02中针对接口的每个方法都要有单独的实现，接口新增方法就要重新修改
 * 此处改为面向整个接口实现
 */
public class Stub {

    public static IUserService getStub() {
        InvocationHandler h = new InvocationHandler() {
            //此处未对method方法进行判断，对接口中所有方法执行统一的invoke实现
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket s = new Socket("127.0.0.1", 8888);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                dos.writeInt((Integer) args[0]);

                s.getOutputStream().write(baos.toByteArray());
                s.getOutputStream().flush();

                DataInputStream dis = new DataInputStream(s.getInputStream());
                int receivedId = dis.readInt();
                String name = dis.readUTF();
                User user = new User(receivedId, name);

                dos.close();
                s.close();
                return user;
            }
        };
        //生成IUserService的动态代理类，对接口中的每个方法调用时执行代理方法
        Object o = Proxy.newProxyInstance(IUserService.class.getClassLoader(), new Class[]{IUserService.class}, h);
        System.out.println(o.getClass().getName());
        System.out.println(o.getClass().getInterfaces()[0]);
        return (IUserService)o;
    }
}
